{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qEIr4kn4W6Zs"
      },
      "source": [
        "# Sharpness-Aware Minimization (SAM)\n",
        "\n",
        "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google-deepmind/optax/blob/main/examples/sam.ipynb)\n",
        "\n",
        "\n",
        "This serves a testing ground for a simple SAM type optimizer implementation in JAX with existing apis."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "AxR7ryYMXHcr"
      },
      "outputs": [],
      "source": [
        "import jax\n",
        "import jax.numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import optax\n",
        "import chex\n",
        "from optax import contrib"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ImgJJV9_iq-v"
      },
      "source": [
        "## Transparent Mode\n",
        "\n",
        "This implementation of SAM can be used in two different modes: transparent and opaque.\n",
        " - Transparent mode exposes all gradient updates (described below) to the training loop, but it is easier to set up.\n",
        " - Opaque mode hides the adversarial updates from the training loop, which is necessary when other state depends on the updates, such as BatchNorm parameters.\n",
        "\n",
        "Opaque mode is slightly more work to set up, so we will start with transparent mode."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TocZvhcDJoyY"
      },
      "source": [
        "One way to describe what SAM does is that it does some number of steps (usually 1) of adversarial updates, followed by an outer gradient update.\n",
        "\n",
        "What this means is that we have to do a bunch of steps:\n",
        "\n",
        "\n",
        "    # adversarial step\n",
        "    params = params + sam_rho * normalize(gradient)\n",
        "\n",
        "    # outer update step\n",
        "    params = cache - learning_rate * gradient\n",
        "    cache = params\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7-p_W8vkhnO1"
      },
      "source": [
        "To actually use SAM then, you create your adversarial optimizer, here SGD with normalized gradients, an outer optimzer, and then wrap them with SAM.\n",
        "\n",
        "The drop-in SAM optimizer described in the paper uses SGD for both optimizers."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ueMKkNw7jLNJ"
      },
      "outputs": [],
      "source": [
        "lr = 0.01\n",
        "rho = 0.1\n",
        "opt = optax.sgd(lr)\n",
        "adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "sam_opt = contrib.sam(opt, adv_opt, sync_period=2)  # This is the drop-in SAM optimizer.\n",
        "\n",
        "sgd_opt = optax.sgd(lr)  # Baseline SGD optimizer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jgFuHGHPAIfU"
      },
      "source": [
        "However, it is possible to use SGD for the adversarial optimizer, and, for example, SGD with momentum for the outer optimizer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TsLVwjHywg55"
      },
      "outputs": [],
      "source": [
        "def sam_mom(lr=1e-3, momentum=0.1, rho=0.1, sync_period=2):\n",
        "  opt = optax.sgd(lr, momentum=momentum)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period)\n",
        "\n",
        "mom = 0.9\n",
        "sam_mom_opt = sam_mom(lr, momentum=mom)\n",
        "mom_opt = optax.sgd(lr, momentum=mom)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "K6CCwKIIASsN"
      },
      "source": [
        "It's even possible to use Adam for **both** optimizers. In this case, we'll need to increase the number of adversarial steps between syncs, but the resulting optimization will still be much faster than using SGD by itself with SAM."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0FesjRbUsT80"
      },
      "outputs": [],
      "source": [
        "def sam_adam(lr=1e-3, b1=0.9, b2=0.999, rho=0.03, sync_period=5):\n",
        "  \"\"\"A SAM optimizer using Adam for the outer optimizer.\"\"\"\n",
        "  opt = optax.adam(lr, b1=b1, b2=b2)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.adam(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period)\n",
        "\n",
        "sam_adam_opt = sam_adam(lr)\n",
        "adam_opt = optax.adam(lr)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DyTChHZr2Yw6"
      },
      "source": [
        "We'll set up a simple test problem below, we're going to try to optimize a sum of two exponentials that has two minima, one at (0,0) and another at (2,0) and compare the performance of both SAM and ordinary SGD."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PSE3mM2FZGio"
      },
      "outputs": [],
      "source": [
        "# An example 2D loss function. It has two minima at (0,0) and (2,0).\n",
        "# Both points attain almost zero loss value, but the first one is much sharper.\n",
        "\n",
        "def loss(params):\n",
        "  x, y = params\n",
        "  return -np.exp(-(x - 2)**2 - y**2) - 1.0*np.exp(-((x)**2 + (y)**2*100))\n",
        "\n",
        "x, y = np.meshgrid(np.linspace(0, 2, 100), np.linspace(0, 2, 100))\n",
        "l = loss((x, y))\n",
        "plt.matshow(l)\n",
        "plt.xticks([0, 50, 100], [0, 1, 2])\n",
        "plt.yticks([0, 50, 100], [0, 1, 2])\n",
        "plt.title('Loss Surface')\n",
        "plt.show();"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Zi3tzM1AZbN_"
      },
      "outputs": [],
      "source": [
        "params = np.array([-0.4, -0.4])\n",
        "\n",
        "@chex.dataclass\n",
        "class Store:\n",
        "  params: chex.Array\n",
        "  state: optax.OptState\n",
        "  step: int = 0\n",
        "\n",
        "sam_store = Store(params=params, state=sam_opt.init(params))\n",
        "sgd_store = Store(params=params, state=sgd_opt.init(params))\n",
        "sam_mom_store = Store(params=params, state=sam_mom_opt.init(params))\n",
        "mom_store = Store(params=params, state=mom_opt.init(params))\n",
        "sam_adam_store = Store(params=params, state=sam_adam_opt.init(params))\n",
        "adam_store = Store(params=params, state=adam_opt.init(params))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UhFr0AwqZjRk"
      },
      "outputs": [],
      "source": [
        "def make_step(opt):\n",
        "  @jax.jit\n",
        "  def step(store):\n",
        "    value, grads = jax.value_and_grad(loss)(store.params)\n",
        "    updates, state = opt.update(grads, store.state, store.params)\n",
        "    params = optax.apply_updates(store.params, updates)\n",
        "    return store.replace(\n",
        "        params=params,\n",
        "        state=state,\n",
        "        step=store.step+1), value\n",
        "  return step"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bTkjju6IinJx"
      },
      "outputs": [],
      "source": [
        "sam_step = make_step(sam_opt)\n",
        "sgd_step = make_step(sgd_opt)\n",
        "\n",
        "sam_mom_step = make_step(sam_mom_opt)\n",
        "mom_step = make_step(mom_opt)\n",
        "\n",
        "sam_adam_step = make_step(sam_adam_opt)\n",
        "adam_step = make_step(adam_opt)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MEF-PriWcLSa"
      },
      "outputs": [],
      "source": [
        "sam_vals = []\n",
        "sam_params = []\n",
        "sgd_vals = []\n",
        "sgd_params = []\n",
        "\n",
        "sam_mom_vals = []\n",
        "sam_mom_params = []\n",
        "mom_vals = []\n",
        "mom_params = []\n",
        "\n",
        "sam_adam_vals = []\n",
        "sam_adam_params = []\n",
        "adam_vals = []\n",
        "adam_params = []"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8Em3xy9PaEbH"
      },
      "outputs": [],
      "source": [
        "T = 8000\n",
        "for i in range(T):\n",
        "  sam_store, sam_val = sam_step(sam_store)\n",
        "  sgd_store, sgd_val = sgd_step(sgd_store)\n",
        "  sam_mom_store, sam_mom_val = sam_mom_step(sam_mom_store)\n",
        "  mom_store, mom_val = mom_step(mom_store)\n",
        "  sam_adam_store, sam_adam_val = sam_adam_step(sam_adam_store)\n",
        "  adam_store, adam_val = adam_step(adam_store)\n",
        "\n",
        "  sam_vals.append(sam_val)\n",
        "  sgd_vals.append(sgd_val)\n",
        "  sam_mom_vals.append(sam_mom_val)\n",
        "  mom_vals.append(mom_val)\n",
        "  sam_adam_vals.append(sam_adam_val)\n",
        "  adam_vals.append(adam_val)\n",
        "\n",
        "  sam_params.append(sam_store.params)\n",
        "  sgd_params.append(sgd_store.params)\n",
        "  sam_mom_params.append(sam_mom_store.params)\n",
        "  mom_params.append(mom_store.params)\n",
        "  sam_adam_params.append(sam_adam_store.params)\n",
        "  adam_params.append(adam_store.params)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sCrf_qJzdDmk"
      },
      "outputs": [],
      "source": [
        "ts = np.arange(T)\n",
        "fig, axs = plt.subplots(6, figsize=(10, 12))\n",
        "axs[0].plot(ts, sgd_vals, label='SGD')\n",
        "axs[0].plot(ts[::2], sam_vals[0::2], label='SAM Outer Loss', lw=3, zorder=100)\n",
        "axs[0].plot(ts[1::2], sam_vals[1::2], label='SAM Adv Loss', alpha=0.5)\n",
        "axs[0].legend();\n",
        "\n",
        "axs[1].plot(ts, sgd_vals, label='SGD')\n",
        "axs[1].plot(ts[::2] / 2, sam_vals[::2], label='1/2 SAM', lw=3)\n",
        "axs[1].legend();\n",
        "\n",
        "axs[2].plot(ts, mom_vals, label='Mom')\n",
        "axs[2].plot(ts[::2], sam_mom_vals[::2], label='SAM Mom Outer Loss', lw=3, zorder=100)\n",
        "axs[2].plot(ts[1::2], sam_mom_vals[1::2], label='SAM Mom Adv Loss', alpha=0.5)\n",
        "axs[2].legend();\n",
        "\n",
        "axs[3].plot(ts, mom_vals, label='Mom')\n",
        "axs[3].plot(ts[::2] / 2, sam_mom_vals[::2], label='1/2 SAM Mom', lw=3)\n",
        "axs[3].legend();\n",
        "\n",
        "axs[4].plot(ts, adam_vals, label='Adam')\n",
        "axs[4].plot(ts[::5], sam_adam_vals[::5], label='SAM Adam Outer Loss', lw=3, zorder=100)\n",
        "axs[4].plot(ts[4::5], sam_adam_vals[4::5], label='SAM Adam Adv Loss', alpha=0.5)\n",
        "axs[4].legend();\n",
        "\n",
        "axs[5].plot(ts, adam_vals, label='Adam')\n",
        "axs[5].plot(ts[::5] / 5, sam_adam_vals[::5], label='1/5 SAM Adam', lw=3)\n",
        "axs[5].legend();"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kEmX6vdp_n50"
      },
      "source": [
        "On this problem, SAM Mom is the fastest of the three SAM optimizers in terms of real steps, but in terms of outer gradient steps, SAM Adam is slightly faster, since it has 4 inner gradient steps for every outer gradient step, compared with 1 inner per outer for SAM and SAM Mom."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "o1kIeonUeA0x"
      },
      "outputs": [],
      "source": [
        "fig, axs = plt.subplots(ncols=3, figsize=(8 * 3, 6))\n",
        "axs[0].plot(*np.array(sgd_params).T, label='SGD')\n",
        "axs[0].plot(*np.array(sam_params)[1::2].T, label='SAM Outer Steps', zorder=100)\n",
        "axs[0].plot(*np.array(sam_params)[::2].T, label='SAM Adv Steps', alpha=0.5)\n",
        "axs[0].legend(loc=4);\n",
        "\n",
        "axs[1].plot(*np.array(mom_params).T, label='Mom')\n",
        "axs[1].plot(*np.array(sam_mom_params)[1::2].T, label='SAM Mom Outer Steps', zorder=100)\n",
        "axs[1].plot(*np.array(sam_mom_params)[::2].T, label='SAM Mom Adv Steps', alpha=0.5)\n",
        "axs[1].legend(loc=4);\n",
        "\n",
        "axs[2].plot(*np.array(adam_params).T, label='Adam')\n",
        "axs[2].plot(*np.array(sam_adam_params)[4::5].T, label='SAM Adam Outer Steps', zorder=100)\n",
        "axs[2].plot(*np.array(sam_adam_params)[3::5].T, label='SAM Adam Adv Steps', alpha=0.5)\n",
        "axs[2].legend(loc=4);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8nVNiUsweApJ"
      },
      "source": [
        "As you can see, all three SAM optimizers find the smooth optimum, while all three standard optimizers get stuck in the sharp optimum.\n",
        "\n",
        "SAM and SAM Mom follow fairly similar paths (although SAM Mom is much faster), but Sam Adam actually passes through the sharp optimum on the way to the smooth optimum.\n",
        "\n",
        "The adversarial steps are quite different between the three SAM optimizers, demonstrating that the choice of both outer and inner optimizer have strong impacts on how the loss landscape gets explored."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0s8UWJB-joV-"
      },
      "source": [
        "## Opaque Mode\n",
        "\n",
        "Here, we'll demonstrate how to use opaque mode on the same setting.\n",
        "\n",
        "The main difference is that we need to pass a gradient function to the update call. The gradient function needs to take as arguments params and an integer (indicating the current adversarial step). It's generally safe to ignore the second argument:\n",
        "```python\n",
        "grad_fn = jax.grad(\n",
        "    lambda params, _: loss(params, batch, and_other_args, to_loss))\n",
        "updates, sam_state = sam_opt.update(updates, sam_state, params, grad_fn=grad_fn)\n",
        "params = optax.apply_updates(params, updates)\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EwXxXOFVkjou"
      },
      "source": [
        "Here's the opaque drop-in SAM optimizer again.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UMvJqqxRjmIF"
      },
      "outputs": [],
      "source": [
        "lr = 0.01\n",
        "rho = 0.1\n",
        "opt = optax.sgd(lr)\n",
        "adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "sam_opt = contrib.sam(opt, adv_opt, sync_period=2, opaque_mode=True)\n",
        "\n",
        "sgd_opt = optax.sgd(lr)  # Baseline SGD optimizer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "woThldyjjmIH"
      },
      "source": [
        "Here's an opaque momentum SAM optimizer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YcaxX4-4jmIH"
      },
      "outputs": [],
      "source": [
        "def sam_mom(lr=1e-3, momentum=0.1, rho=0.1, sync_period=2):\n",
        "  opt = optax.sgd(lr, momentum=momentum)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period, opaque_mode=True)\n",
        "\n",
        "mom = 0.9\n",
        "sam_mom_opt = sam_mom(lr, momentum=mom)\n",
        "mom_opt = optax.sgd(lr, momentum=mom)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0MXyU4WrjmIH"
      },
      "source": [
        "Here's an opaque Adam-based SAM optimizer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Fb8Cy5xgjmIJ"
      },
      "outputs": [],
      "source": [
        "def sam_adam(lr=1e-3, b1=0.9, b2=0.999, rho=0.03, sync_period=5):\n",
        "  \"\"\"A SAM optimizer using Adam for the outer optimizer.\"\"\"\n",
        "  opt = optax.adam(lr, b1=b1, b2=b2)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.adam(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period, opaque_mode=True)\n",
        "\n",
        "sam_adam_opt = sam_adam(lr)\n",
        "adam_opt = optax.adam(lr)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-z4NxcZujmIJ"
      },
      "outputs": [],
      "source": [
        "params = np.array([-0.4, -0.4])\n",
        "\n",
        "@chex.dataclass\n",
        "class Store:\n",
        "  params: chex.Array\n",
        "  state: optax.OptState\n",
        "  step: int = 0\n",
        "\n",
        "sam_store = Store(params=params, state=sam_opt.init(params))\n",
        "sgd_store = Store(params=params, state=sgd_opt.init(params))\n",
        "sam_mom_store = Store(params=params, state=sam_mom_opt.init(params))\n",
        "mom_store = Store(params=params, state=mom_opt.init(params))\n",
        "sam_adam_store = Store(params=params, state=sam_adam_opt.init(params))\n",
        "adam_store = Store(params=params, state=adam_opt.init(params))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bwLv3UTCjmIK"
      },
      "outputs": [],
      "source": [
        "def make_step(opt):\n",
        "  @jax.jit\n",
        "  def step(store):\n",
        "    value, grads = jax.value_and_grad(loss)(store.params)\n",
        "    if isinstance(store.state, contrib.SAMState):\n",
        "      updates, state = opt.update(\n",
        "          grads, store.state, store.params,\n",
        "          grad_fn=jax.grad(lambda p, _: loss(p)))  # NOTICE THE ADDITIONAL grad_fn ARGUMENT!\n",
        "    else:\n",
        "      updates, state = opt.update(grads, store.state, store.params)\n",
        "    params = optax.apply_updates(store.params, updates)\n",
        "    return store.replace(\n",
        "        params=params,\n",
        "        state=state,\n",
        "        step=store.step+1), value\n",
        "  return step"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VRJiF7TWjmIK"
      },
      "outputs": [],
      "source": [
        "sam_step = make_step(sam_opt)\n",
        "sgd_step = make_step(sgd_opt)\n",
        "\n",
        "sam_mom_step = make_step(sam_mom_opt)\n",
        "mom_step = make_step(mom_opt)\n",
        "\n",
        "sam_adam_step = make_step(sam_adam_opt)\n",
        "adam_step = make_step(adam_opt)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cwSnRxfQjmIK"
      },
      "outputs": [],
      "source": [
        "sam_vals = []\n",
        "sam_params = []\n",
        "sgd_vals = []\n",
        "sgd_params = []\n",
        "\n",
        "sam_mom_vals = []\n",
        "sam_mom_params = []\n",
        "mom_vals = []\n",
        "mom_params = []\n",
        "\n",
        "sam_adam_vals = []\n",
        "sam_adam_params = []\n",
        "adam_vals = []\n",
        "adam_params = []"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "m20mYyBHjmIK"
      },
      "outputs": [],
      "source": [
        "T = 4000\n",
        "for i in range(T):\n",
        "  sam_store, sam_val = sam_step(sam_store)\n",
        "  sgd_store, sgd_val = sgd_step(sgd_store)\n",
        "  sam_mom_store, sam_mom_val = sam_mom_step(sam_mom_store)\n",
        "  mom_store, mom_val = mom_step(mom_store)\n",
        "  sam_adam_store, sam_adam_val = sam_adam_step(sam_adam_store)\n",
        "  adam_store, adam_val = adam_step(adam_store)\n",
        "\n",
        "  sam_vals.append(sam_val)\n",
        "  sgd_vals.append(sgd_val)\n",
        "  sam_mom_vals.append(sam_mom_val)\n",
        "  mom_vals.append(mom_val)\n",
        "  sam_adam_vals.append(sam_adam_val)\n",
        "  adam_vals.append(adam_val)\n",
        "\n",
        "  sam_params.append(sam_store.params)\n",
        "  sgd_params.append(sgd_store.params)\n",
        "  sam_mom_params.append(sam_mom_store.params)\n",
        "  mom_params.append(mom_store.params)\n",
        "  sam_adam_params.append(sam_adam_store.params)\n",
        "  adam_params.append(adam_store.params)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zlDP-42ajmIK"
      },
      "outputs": [],
      "source": [
        "ts = np.arange(T)\n",
        "fig, axs = plt.subplots(6, figsize=(10, 12))\n",
        "axs[0].plot(ts, sgd_vals, label='SGD')\n",
        "axs[0].plot(ts, sam_vals, label='SAM', lw=3, zorder=100)\n",
        "axs[0].legend();\n",
        "\n",
        "axs[1].plot(ts, sgd_vals, label='SGD')\n",
        "axs[1].plot(ts * 2, sam_vals, label='2 * SAM', lw=3)\n",
        "axs[1].legend();\n",
        "\n",
        "axs[2].plot(ts, mom_vals, label='Mom')\n",
        "axs[2].plot(ts, sam_mom_vals, label='SAM Mom', lw=3, zorder=100)\n",
        "axs[2].legend();\n",
        "\n",
        "axs[3].plot(ts, mom_vals, label='Mom')\n",
        "axs[3].plot(ts * 2, sam_mom_vals, label='2 * SAM Mom', lw=3)\n",
        "axs[3].legend();\n",
        "\n",
        "axs[4].plot(ts, adam_vals, label='Adam')\n",
        "axs[4].plot(ts, sam_adam_vals, label='SAM Adam', lw=3, zorder=100)\n",
        "axs[4].legend();\n",
        "\n",
        "axs[5].plot(ts, adam_vals, label='Adam')\n",
        "axs[5].plot(ts * 5, sam_adam_vals, label='5 * SAM Adam', lw=3)\n",
        "axs[5].legend();"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NLAJFJ-SjmIK"
      },
      "source": [
        "The behavior is identical to transparent mode, but the percieved number of gradient steps is half as many as in transparent mode (or 1/5 as many for SAM Adam)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mY5FzqMLjmIK"
      },
      "outputs": [],
      "source": [
        "fig, axs = plt.subplots(ncols=3, figsize=(8 * 3, 6))\n",
        "axs[0].plot(*np.array(sgd_params).T, label='SGD')\n",
        "axs[0].plot(*np.array(sam_params).T, label='SAM', zorder=100)\n",
        "axs[0].legend(loc=4);\n",
        "\n",
        "axs[1].plot(*np.array(mom_params).T, label='Mom')\n",
        "axs[1].plot(*np.array(sam_mom_params).T, label='SAM Mom')\n",
        "axs[1].legend(loc=4);\n",
        "\n",
        "axs[2].plot(*np.array(adam_params).T, label='Adam')\n",
        "axs[2].plot(*np.array(sam_adam_params).T, label='SAM Adam')\n",
        "axs[2].legend(loc=4);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "P_MjRgofjmIK"
      },
      "source": [
        "The behavior is identical to transparent mode here as well, but we don't get to see the adversarial updates."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "last_runtime": {
        "build_target": "//learning/grp/tools/ml_python:ml_notebook",
        "kind": "private"
      },
      "private_outputs": true,
      "provenance": [
        {
          "file_id": "1ap7lwdf3vgoQdyNogmSVfncYZcH1ijch",
          "timestamp": 1697129954516
        }
      ],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
